package com.lyn.dwjhb.convertor;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.List;

import org.apache.commons.dbutils.QueryRunner;

import com.lyn.dwjhb.model.SysUserDept;

public class UserDeptConvertor extends BaseConvertor{
	public UserDeptConvertor() {
		super();
	}
	
	public UserDeptConvertor(QueryRunner rq) {
		super(rq);
	}



	public static int sorting = 100;
	private String getInsertSql(SysUserDept sysUserDept) {
		String sql = "insert into sys_user_dept (guid, gmt_create, gmt_modified, sorting, "
				+ "user_id, user_name, dept_id, dept_name, dept_type) values("
				+ "sys_guid(), sysdate, sysdate, "+sorting+","
				+ wrapper(sysUserDept.getUserId())+","+ wrapper(sysUserDept.getUserName())+","
				+ wrapper(sysUserDept.getDeptId())+","+ wrapper(sysUserDept.getDeptName())+","
				+ wrapper(sysUserDept.getDeptType())+");";
		sorting+=10;
		return sql;
	}
	
	
	
	public void toFile(List<SysUserDept> list) {
		File file = new File("resource/PROC_INSERT_SYS_USER_DEPT.sql");
		if(!file.exists()) {
			file.delete();
		}
        try {
        	file.createNewFile();
        } catch (IOException e) {
            e.printStackTrace();
        }
        
        try(
            FileOutputStream fos = new FileOutputStream(file);
            OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
        	BufferedWriter bw = new BufferedWriter(osw);) {
        	String sql = "create or replace procedure PROC_INSERT_SYS_USER_DEPT is";
        	this.writeLine(bw, sql);
        	sql = "begin";
        	this.writeLine(bw, sql);
        	sql = "insert into sys_user_dept (guid, gmt_create, gmt_modified, sorting, "
        			+ "user_id, user_name, dept_id, dept_name, dept_type) values("
        			+ "sys_guid(), sysdate, sysdate, 90,"
        			+ "'uid705db7bf13b40bcc10a7fa9', 'admin', "
        			+ "'9ecb4266ea8146a09a40dedf0928319d', '广西电网公司', '区级');";
        	this.writeLine(bw, sql);
        	for(SysUserDept sysUserDept : list) {
        		sql = getInsertSql(sysUserDept);
        		this.writeLine(bw, sql);
    		}
        	sql = "commit;";
        	this.writeLine(bw, sql);
        	sql = "end PROC_INSERT_SYS_USER_DEPT;";
        	this.writeLine(bw, sql);
        } catch (Exception e) {
            e.printStackTrace(); 
        } 
	}
	
	
	
}
